var interval = 0;

$(function() {
	$('#login-btn').click(function() { login(); } );
	$('#logout-btn').click(function() { logout(); } );
	$('#start-btn').click(function() { start_game(); } );
	
	$('#login-btn').attr("disabled", false);
	$('#logout-btn').attr("disabled", true);
	
	$('#userName').focus();
	$('#userName').keyup(function(event) {
		if (event.keyCode == 13 && !$('#login-btn').attr('disabled')) {
			$('#login-btn').click();
		}
	});
	
	get_users();
	
	if ($('#game-mems').val().length == 0)
		$('#start-btn').attr("disabled", true);
	
	interval = setInterval("refresh()", 2000);
});

// gets boolean true or false called 'success'
function login() {
  $.ajax({
    url: "/joinGroup",
    type: "POST",
    dataType: "json",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    data: {
      "userName": $('#userName').val(),
      "gid": $('#gid').val()
    },
    async: true,
    success: function(result) {
      if (result.error) {
          alert("Internal Server Error: See log");
          console.log(result.error);
      } else {
        if (result.success == true) {
          $('#login-name').val($('#userName').val());
          $('#userName').val("");
          $('#login-btn').attr('disabled', true);
          $('#logout-btn').attr('disabled', false);
          console.log("login() success as: " + $('#login-name').val());
          get_users();
        } else {
          alert("Could  not log in to server.");
        }
      }
    },
    error: function(xhr, status, errorThrown) {
      alert("Error during login() type '" + status + "':\n" + errorThrown);
    }
  });
}

function logout() {
	$.ajax({
		url: "/leaveGroup",
		type: "POST",
		dataType: "json",
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
		data: {
			"userName": $('#login-name').val(),
			"gid": $('#gid').val()
		},
		async: true,
		success: function(result) {
			$('#login-name').val("");
			$('#login-btn').attr('disabled', false);
			$('#logout-btn').attr('disabled', true);
			$('#start-btn').attr("disabled", true);
			get_users();
		},
		error: function(xhr, status, errorThrown) {
			alert("Error during logout() type " + status + ":\n" + errorThrown);
		}
	});
}

// gets an array of strings for all 'logged in'/'connected' users.  array is called 'users'
// needs gid
function get_users() {
  $.ajax({
    url: "/getUsers",
    type: "POST",
    dataType: "json",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    data: {
      "gid": $('#gid').val()
    },
    async: true,
    success: function(result) {
      if (result.error) {
        alert("Internal Server Error: See log");
        console.log(result.error);
      } else {
    	$('#game-mems').val("");
        if (result.users) {
        	console.log("get_users() success: " + result.users);
        	if (result.users.length >= 5) {
        		$('#login-btn').attr("disabled", false);
        	}
        	
        	if (result.users.length > 0) {
	        	for (var i in result.users) {
	        		$('#game-mems').val($('#game-mems').val() + result.users[i] + "\n");
	        	}	        	
        	}
        	
        	if (result.users.length > 1)
        		$('#start-btn').attr("disabled", false);
        	else
        		$('#start-btn').attr("disabled", true);
        }
      }
    },
    error: function(xhr, status, errorThrown) {
      alert("Error during get_users() type '" + status + "':\n" + errorThrown);
    }
  });
}

// gets boolean 'success', and int 'gid' (if success is true).  Matt's code sets eid to -1.
function start_game() {
  $.ajax({
    url: "/startGame",
    type: "POST",
    dataType: "json",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    data: {
      "gid": $('#gid').val()
    },
    async: true,
    success: function(result) {
      if (result.error) {
        alert("Internal Server Error: See log");
        console.log(result.error);
      } else {
        if (result.success == true) {
        	console.log("start_game() success");
          refresh();
        }
        else
          alert("Could not start game.");
      }
    },
    error: function(xhr, status, errorThrown) {
      alert("Error during start_game() type '" + status + "':\n" + errorThrown);
    }
  });
}

// gets integer that's the difference between our eid and the current game's eid.  'eid_dif'
// needs gid and eid
function refresh() {
  $.ajax({
    url: "/refresh",
    type: "POST",
    dataType: "json",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    data: {
      "gid": $('#gid').val(),
      "eid": $('#eid').val()
    },
    async: true,
    success: function(result) {
      if (result.error) {
        console.log("Error during refresh. result.error is: \n" + result.error);
      } else {   	  
    	if ($('#login-name').val() != "")
    		$('#current-user').html("Welcome, " + $('#login-name').val());
    	else
    		$('#current-user').html("<br>");
    		
        if (result.eid_dif > 0) {
          $('#eid').val(+$('#eid').val() + +result.eid_dif);
          get_users();
          
        } else if (result.eid_dif < 0 && $('#login-name').val().length > 0) {
          var url = String(window.location) + "board.html?userName=" + $('#login-name').val() + "&gid=" + $('#gid').val();
          window.open(url, "_top");
        }
      }
    },
    error: function(xhr, status, errorThrown) {
      alert("Connection error during refresh() type '" + status + "':\n" + errorThrown);
    }
  });
}
